<?php
/*
 * @Description: file content
 * @FilePath: \auxface_certificate\app\certificate\controller\admin\v1\flow\Form.php
 */

declare(strict_types=1);

namespace app\certificate\controller\admin\v1\flow;

use think\facade\Db;
use think\Request;

class Form
{
    /**
     * @Description: 
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['flowUuid', '=', $data['flowUuid']]
        ];

        if (!empty($data['name'])) array_push($where, ['name', 'like', $data['name'] . "%"]);

        $list = DB::table('certificate_flowForm')
        ->where($where)
        ->field(['name', 'remark', 'inDate', 'uuid', 'flowOrder',
            "CASE WHEN formData  <> '' THEN 1  ELSE 0 END AS formData"
        ])
        ->order('id desc')
        ->page((int)$page, (int)$limit)
        ->select()->toArray();
        foreach ($list as &$item) {
            $item['workerCount'] = DB::table('certificate_flowFormWorker')->where(['isDelete' => 0, 'flowFormUuid' => $item['uuid']])->count();
        }

        $count = DB::table('certificate_flowForm')
            ->where($where)
            ->count();

        $data = compact('list', 'count');

        return result(SUCCESS, $data);
    }
    /**
     * @Description: 
     * @param {Request} $request
     */
    public function create(Request $request)
    {
        $data = $request->data;
        $linkForms = [];
        if(isset($data['linkForms'])) {
            $data['linkForms'] = $data['linkForms'] ?: [];
        
            $linkForms = json_encode($data['linkForms'], JSON_UNESCAPED_UNICODE) ;
            $linkFormList = DB::table('certificate_flowForm')->whereIn('uuid', $data['linkForms'])->select()->toArray() ?: [];
            if(count($linkFormList) != count($data['linkForms'])) {
                return result(FAIL, '', "关联表单不存在");
            }
            foreach ($linkFormList as $item) {
                if($item['flowOrder'] > $data['flowOrder']) {
                    return result(FAIL, '', "流程顺序不能小于{$data['flowOrder']}!");
                }
            }
        }
        // $isExist = DB::table('certificate_flowForm')->where('flowUuid', $data['flowUuid'])->where('isDelete', 0)->where('formType', 1)->find();
        // if(!$isExist && $data['formType'] != 1) {
        //     return result(FAIL, '', "请先新增申请表单再操作其他表单");
        // }
        // //是否已经存在申请表单
        // if($data['formType'] == 1 && $isExist) {
        //     return result(FAIL, '', "申请表单已经存在，不允许有多个");
        // }
       
        $insert =  [
            'uuid' => createUuid(),
            'projectCode' => $request->prjCode,
            'corpCode' => $request->corpCode,
            'name' => $data['name'],
            'remark' => $data['remark'] ?? '',
            'flowOrder' => $data['flowOrder'] ?? '',
            'flowUuid' => $data['flowUuid'] ?? '',
            'type' => $data['type'] ?? '',
            'signType' => $data['signType'] ?? '',
            'showOrder' => $data['showOrder'] ?? '',
            'linkForms' =>  $linkForms,
            'subtitle' => $data['subtitle'] ?? '',
            'formType' => $data['formType'] ?? '',
        ];

       
        DB::table('certificate_flowForm')->insert($insert);

        return result(SUCCESS, ['uuid' => $insert['uuid'], 'inDate' => date('Y-m-d H:i:s')], '添加成功!');
    }

    /**
     * @Description: 修改
     */
    public function update(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $linkForms = [];
        if(isset($data['linkForms'])) {
            $data['linkForms'] = $data['linkForms'] ?: [];
            $linkForms = json_encode($data['linkForms'], JSON_UNESCAPED_UNICODE) ?: [];
            $linkFormList = DB::table('certificate_flowForm')->whereIn('uuid', $data['linkForms'])->select()->toArray() ?: [];
            if(count($linkFormList) != count($data['linkForms'])) {
                return result(FAIL, '', "关联表单不存在");
            }
            foreach ($linkFormList as $item) {
                if($item['flowOrder'] > $data['flowOrder']) {
                    return result(FAIL, '', "不能关联顺序大于或者等于{$data['flowOrder']}的表单!");
                }
            }
        }

        // $isExist = DB::table('certificate_flowForm')->where('flowUuid', $data['flowUuid'])->where('isDelete', 0)->where('formType', 1)->find();
        // if(!$isExist && $data['formType'] != 1) {
        //     return result(FAIL, '', "请先新增申请表单再操作其他表单");
        // }

        // if($data['formType'] == 1) {
        //     $isExist = DB::table('certificate_flowForm')->where('flowUuid', $data['flowUuid'])->where('isDelete', 0)->where('formType', 1)->where('uuid', '<>', $uuid)->find();
        //     if($isExist) return result(FAIL, '', "申请表单已经存在，不允许有多个");
        // }

        $cehck = DB::table('certificate_flowForm')->where([
            ['uuid', '<>', $uuid],
            ['name', '=', $data['name']],
            ['isDelete', '=', 0],
        ])->value('id');
        if ($cehck) return result(FAIL, '', '名称已存在,无法修改!');
        $updateData = [
            'name' => $data['name'],
            'remark' => $data['remark'] ?? '',
            'flowOrder' => $data['flowOrder'] ?? '',
            'flowUuid' => $data['flowUuid'] ?? '',
            'type' => $data['type'] ?? '',
            'signType' => $data['signType'] ?? '',
            'showOrder' => $data['showOrder'] ?? '',
            'linkForms' => $linkForms ?? [],
            'subtitle' => $data['subtitle'],
            'formType' => $data['formType'] ?? '',
        ];
        DB::table('certificate_flowForm')->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, '', '更改成功');
    }

    public function destroy(Request $request)
    {
        $data = $request->data;
        DB::table('certificate_flowForm')->where('uuid', $data['uuid'])->update(['isDelete' => 1]);
        return result(SUCCESS, '', '删除成功');
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $data = DB::table('certificate_flowForm')->where('uuid', $uuid)->field(['inDate', 'corpCode', 'name', 'remark', 'uuid', 'flowOrder', 'flowUuid', 'type', 'signType', 'showOrder', 'linkForms','formData','subtitle','formType'])->find();
        if (!$data)  return result(FAIL, '', '数据不存在');
        $data['linkForms'] = json_decode($data['linkForms'], true);
        $data['formData'] = json_decode($data['formData'], true);
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 获取人员数据
     * @param {Request} $request
     */
    public function getWorker(Request $request)
    {
        $data = $request->data;

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) array_push($where, ['corpCode', '=', $request->corpCode]);

        $attendanceWhere = [
            ['entryTime', '<>', '0000-00-00 00:00:00'],
            ['exitTime', '=', '0000-00-00 00:00:00'],
        ];

        $list = DB::table('certification_projectWorker')
            ->where(array_merge($where, $attendanceWhere))
            ->field(['teamName', 'workerName', 'teamSysNo', 'wxappUserUuid', 'corpName', 'corpCode'])
            ->group(['wxappUserUuid', 'corpCode'])
            ->select()->toArray();

        foreach ($list as $key => $value) {
            if (empty($value['workerName'])) {
                $list[$key]['workerName'] = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['wxappUserUuid'])->value('nickName');
            }
        }
        $list = $this->centerProcess($list);

        $checked = DB::table('certificate_flowFormWorker')
            ->where(['flowFormUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');

        $data = compact('list', 'checked');

        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 修改相关人员
     * @param {Request} $request
     */
    public function changeWorker(Request $request)
    {
        $data = $request->data;
        $flowFormUuid = $data['uuid'];

        $globalData = dataMerge($request->uuid, [
            'flowFormUuid' => $flowFormUuid,
        ]);

        $oldData =  DB::table('certificate_flowFormWorker')
            ->where(['flowFormUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');
        $newData =  array_column($data['value'], 'wxappUserUuid');
        $create = array_diff($newData, $oldData);
        $delete = array_diff($oldData, $newData);

        DB::startTrans();
        try {
            if ($create) {
                foreach ($create as $key => $value) {
                    $insertData[] = array_merge(['wxappUserUuid' => $value, 'uuid' => createUuid()], $globalData);
                }
                DB::table('certificate_flowFormWorker')->insertAll($insertData);
            }
            if ($delete) {
                DB::table('certificate_flowFormWorker')
                    ->where([
                        'wxappUserUuid' => $delete,
                        'flowFormUuid' => $flowFormUuid,
                    ])
                    ->update(['isDelete' => 1]);
            }
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {   
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }
    }

    //人员分类信息     
    private function centerProcess($data)
    {
        if (!$data) return $data;
        $arr = [];
        foreach ($data as $key => $value) {
            if (empty($value['workerName'])) {
                $wxappUserData = DB::table('platform_wxappUser')->where('wxappUserUuid', $value['value'])->field(['nickName'])->findOrEmpty();
                if (empty($wxappUserData)) continue;
                $value['workerName'] = $wxappUserData['nickName'];
                $value['hasWorkerInfo'] = 0;
            }
            $data = [
                'value' => $value['wxappUserUuid'],
                'name' => $value['workerName'],
                'corpCode' => $value['corpCode'],
            ];
            $arr[$value['corpCode']]['name'] = $value['corpName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['name'] = $value['teamName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['children'][] = $data;
        }
        sort($arr);
        foreach ($arr as $key => $value) {
            if (isset($value['children'])) {
                sort($value['children']);
                $arr[$key]['children'] = $value['children'];
            }
        }
        return $arr;
    }
    /**
     * @Description: 获取表单数据
     * @Author: Terry
     * @Date: 2024-11-29 21:53:46
     * @param {Request} $request
     */    
    public function getFormData(Request $request){
        $data = $request->data;
        $uuid = $data['uuid'];
        $data = DB::table('certificate_flowForm')->where('uuid', $uuid)->value('formData');
        $returnData = [
            'formData'=>[
                'fields'=>json_decode($data, true) ?? [],
            ],
        ];
        return result(SUCCESS,$returnData);
    }

    /**
     * @Description: 修改表单数据
     */
    public function changeFormData(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $info = DB::table('certificate_flowForm')->where([
            ['uuid', '=', $uuid],
            ['isDelete', '=', 0],
        ])->find();
        if (!$info) return result(FAIL, '', '流程表单不存在!');
        $updateData = [
            'formData' => html_entity_decode($data['formData']) ?? [],
        ];
        DB::table('certificate_flowForm')->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, '', '更改成功');
    }

     /**
     * @Description: 获取字典
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0]
        ];

        $data['flowList'] = DB::table('certificate_flow')
            ->where($where)
            ->field(['name', 'remark', 'uuid'])
            ->order('id desc')
            ->select();

        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 
     * @param {Request} $request
     */
    public function getAllList(Request $request)
    {
        $data  = $request->data;

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['flowUuid', '=', $data['flowUuid']]
        ];
        if (!empty($data['flowFormUuid'])) array_push($where, ['uuid', '<>', $data['flowFormUuid']]);
        if (!empty($data['name'])) array_push($where, ['name', 'like', $data['name'] . "%"]);

        $list = DB::table('certificate_flowForm')
            ->where($where)
            ->field(['name', 'remark', 'inDate', 'uuid', 'flowOrder'])
            ->order('id desc')
            ->select();

        $count = DB::table('certificate_flowForm')
            ->where($where)
            ->count();

        $data = compact('list', 'count');

        return result(SUCCESS, $data);
    }
}
